package xyz.jcat.webflux.sucurity;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken;
import reactor.core.publisher.Mono;
import xyz.jcat.auth.token.AccessTokenUtils;
import xyz.jcat.auth.token.UserTokenDto;
import xyz.jcat.security.UserRoleAuthenticationToken;

@Slf4j
public class RedisTokenReactiveAuthenticationManager implements ReactiveAuthenticationManager {

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        log.info("come in RedisTokenReactiveAuthenticationManager");
        return Mono.justOrEmpty(authentication)
                .filter(a -> a instanceof BearerTokenAuthenticationToken)
                .cast(BearerTokenAuthenticationToken.class)
                .map(BearerTokenAuthenticationToken::getToken)
                .flatMap((accessToken -> {
                    UserTokenDto userToken = AccessTokenUtils.getUserToken(accessToken);
                    UserRoleAuthenticationToken token = new UserRoleAuthenticationToken(userToken.getId(), userToken.getRoles());
                    token.setAuthenticated(true);
                    return Mono.just(token);
                })).cast(Authentication.class);
    }
}
